#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <syslog.h>

#define FNAME "/tmp/out"
/*
 * 全局变量
 * */
static FILE * fp;
/*
 * 退出函数
 * */
static void daemon_exit(int s)
{
	fclose(fp);
	closelog();
	exit(1);
}

static int daemonize(void)
{
	//定义变量
	int fd;
	pid_t pid;
	//fork
	pid = fork();
	if(pid < 0)
		return -1;
	//子进程成为守护进程
	if(pid == 0)
	{
		//fd = open("/dev/null", O_RDWR);
		fd = open("/home/zhang/out", O_RDWR);
		if(fd < 0)
			return -1;

		dup2(fd, 0);
		dup2(fd, 1);
		dup2(fd, 2);
		if(fd > 2)
			close(fd);

		setsid();

		chdir("/");
		umask(0);

		return 0;
	}
	//父进程退出
	if(pid > 0)
	{
		exit(0);
	}
	return -1;
}


int main()
{
	//定义变量
	int i;
	struct sigaction sa;
	//设置退出函数
	sa.sa_handler = daemon_exit;
	sigemptyset(&sa.sa_mask);
	sigaddset(&sa.sa_mask, SIGQUIT|SIGTERM|SIGINT);
	sa.sa_flags = 0;
	sigaction(SIGINT, &sa, NULL);
	sigaction(SIGTERM, &sa, NULL);
	sigaction(SIGQUIT, &sa, NULL);

	/*
	signal(SIGINT, daemon_exit);
	signal(SIGQUIT, daemon_exit);
	signal(SIGTERM, daemon_exit);
	*/

	//开启系统日志
	openlog("mydaemon", LOG_PID, LOG_DAEMON);
	//创建守护进程
	if(daemonize() < 0)
	{
		syslog(LOG_ERR, "daemonize failed!");
		exit(1);
	}
	else
		syslog(LOG_INFO, "daemonize sucessed!");
	//打开文件
	fp = fopen(FNAME, "w");
	if(fp == NULL)
	{
		syslog(LOG_ERR, "fopen:%s", strerror(errno));
		exit(1);
	}
	else
		syslog(LOG_INFO, "%s was opened!", FNAME);
	//每秒写文件
	for(i = 0; ; i++)
	{
		fprintf(fp, "%d ", i);
		fflush(NULL);
		syslog(LOG_DEBUG, "%d is printed", i);
		sleep(1);
	}

	exit(0);
}
